package me.zingon.doc.controller;


import me.zingon.doc.exception.ServiceException;
import me.zingon.doc.service.ProjectService;
import me.zingon.doc.model.Project;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/**
* Created by ZTCGenerator<zingon@aliyun.com> on 2018-5-31.
*/
@RestController
@RequestMapping("/project")
public class ProjectController extends BaseController{

    @Autowired
    ProjectService projectService;

    @GetMapping("")
    public Object list() throws ServiceException {
        return projectService.listByUser(getUser());
    }

    @PostMapping("")
    public Object save(@RequestBody Project project) throws ServiceException {
        if(project.getId() == null || project.getId() == 0){
            projectService.insertWithUser(project,getUser());
        }else{
            project.setUpdateDate(new Date());
            projectService.update(project);
        }
        return projectService.getById(project.getId());
    }

    @GetMapping("/get/{projectId}")
    public Object get(@PathVariable("projectId")Integer projectId) throws ServiceException {
        return projectService.getById(projectId);
    }

    @GetMapping("/user/{projectId}")
    public Object listUser(@PathVariable("projectId")Integer projectId){
        return projectService.listUserByProjectId(projectId);
    }

    @PostMapping("/user")
    public Object saveUser(@RequestBody Map<String,Object> map) throws ServiceException {
        Integer projectId = (Integer) map.get("projectId");
        String nickname = (String) map.get("nickname");
        String power = (String) map.get("power");
        return projectService.addUser(projectId,nickname,power,getUser());
    }

    @GetMapping("/user/del/{upId}")
    public Object deleteUserProject(@PathVariable("upId")Integer upId) throws ServiceException {
        return projectService.deleteUPByIdWithUser(upId,getUser());
    }


    @GetMapping("/del/{projectId}")
    public Object deleteProject(@PathVariable("projectId")Integer projectId) throws ServiceException {
        return projectService.deleteProjectByIdWithUser(projectId,getUser());
    }

}
